package com.sinochem.yunlian.ship.ucenter.schedule;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.sinochem.yunlian.ship.common.enums.CompanyStatus;
import com.sinochem.yunlian.ship.ucenter.biz.UcShipBiz;
import com.sinochem.yunlian.ship.ucenter.biz.UcShipLocationBiz;
import com.sinochem.yunlian.ship.ucenter.entity.UcShip;
import com.sinochem.yunlian.ship.ucenter.entity.UcShipLocation;
import com.sinochem.yunlian.ship.ucenter.rest.ShipLocationDataRest;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;

@JobHander(value = "shipLocationHandler")
@Service
public class ShipLocationHandler extends IJobHandler {

	@Autowired
	private ShipLocationDataRest shipDataRest;

	@Autowired
	private UcShipBiz ucShipBiz;

	@Autowired
	private UcShipLocationBiz ucShipLocationBiz;

	@Value("${ship.location.url}")
	private String shipLocationUrl;

	@Value("${ship.location.key}")
	private String shipLocationKey;

	private DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
	
	/**
     * 每次取船舶的数据
     */
    private static final int DATA_SIZE = 20;

	@Override
	public ReturnT<String> execute(String... params) throws Exception {
		XxlJobLogger.log("XXL-JOB, Hello World.我执行了================哈哈哈哈哈哈哈哈");

		// 查询所有船舶信息
		List<UcShip> shipList = ucShipBiz.findCertifiedShipList(CompanyStatus.PASS.getCode());

		// 分批查询船舶位置信息
		if (shipList != null && shipList.size() > 0) {
			int mod = shipList.size() % DATA_SIZE;
		    int count = shipList.size() / DATA_SIZE;
		    count = mod == 0 ? count : ++count;        
		    for (int i = 0; i < count;) {
		    	int start = DATA_SIZE * i;
	            int end = DATA_SIZE * (++i);
	            end = end >= shipList.size() ? shipList.size() : end;	            
				List<UcShip> ucShipList = shipList.subList(start, end);
				Map<String,Long> shipMap = new HashMap<String,Long>();
				String mmsis = "";
				for(UcShip ucShip: ucShipList){
					shipMap.put(ucShip.getShipMmsi(), ucShip.getId());
					mmsis += ucShip.getShipMmsi()+",";
				}
				List<UcShipLocation> ucShipLocationList = shipDataRest.requestRestUrl(shipLocationUrl, mmsis,
						shipLocationKey, formatter.format(new Date()));
				// 位置数据持久化
				ucShipLocationBiz.addShipLocationBatch(ucShipLocationList, shipMap);
			}
		} else {
			XxlJobLogger.log("yunlian ship 获取认证船数据为空,请核实!");
		}

		return ReturnT.SUCCESS;
	}

}
